import json

import requests
from flask import jsonify, request, g

from common.libs import Helper
from common.libs.Restful import Restful
from common.libs.MemberService import MemberService
from common.models.members import Member, OAuthMemberBind
from common.models.foods.FoodShareHistory import WxShareHistory
from web.controllers.api import api_route

from application import app, db


@api_route.route('/member/login/', methods=['GET', 'POST'])
def index():
    resp = request.values
    code = resp.get('code')
    if not code or len(code) < 1:
        return Restful.param_error('缺少参数')
    # 根据前端传过来的code，和appid、secret获取openid
    openid = MemberService.MemberService.getWechatOpenid(code)
    if not openid:
        return Restful.param_error(msg='调用微信出错，请重试！')

    nickname = resp['nickName'] if resp['nickName'] else ''
    sex = resp['gender'] if resp['gender'] else ''
    avatar = resp['avatarUrl'] if resp['avatarUrl'] else ''

    # 根据openid判断是否已经注册过
    bindInfo = OAuthMemberBind.OauthMemberBind.query.filter_by(openid=openid, type=1).first()
    if bindInfo:
        memberInfo = Member.Member.query.filter_by(id=bindInfo.member_id).first()
        return Restful.success(msg='已经绑定', data={'nickname': memberInfo.nickname})
    else:
        member = Member.Member()
        member.nickname = nickname
        member.avatar = avatar
        member.sex = sex
        member.salt = MemberService.MemberService.geneSalt()
        member.updated_time = member.created_time = Helper.geneDatetime()
        db.session.add(member)
        db.session.commit()

        member_bind = OAuthMemberBind.OauthMemberBind()
        member_bind.member_id = member.id
        member_bind.type = 1
        member_bind.openid = openid
        member_bind.updated_time = member_bind.created_time = Helper.geneDatetime()
        member_bind.extra = ''
        member_bind.client_type = 'weixin'
        db.session.add(member_bind)
        db.session.commit()
    token = "%s#%s" % (MemberService.MemberService.geneAuthCode(member), member.id)
    return Restful.success(data={'token': token})


@api_route.route('/member/checkreg/', methods=['POST'])
def checkreg():
    resp = request.values
    code = resp.get('code')
    if not code or len(code) < 1:
        return Restful.param_error('缺少参数')
    # 根据前端传过来的code，和appid、secret获取openid
    openid = MemberService.MemberService.getWechatOpenid(code)
    if not openid:
        return Restful.param_error(msg='调用微信出错，请重试！')

    # 根据openid判断是否已经注册过
    bindInfo = OAuthMemberBind.OauthMemberBind.query.filter_by(openid=openid, type=1).first()
    if not bindInfo:
        return Restful.format_error(msg='未绑定', code=403)
    memberInfo = Member.Member.query.filter_by(id=bindInfo.member_id).first()
    if not memberInfo:
        return Restful.format_error(msg='未查询到绑定信息', code=403)

    token = "%s#%s" % (MemberService.MemberService.geneAuthCode(memberInfo), memberInfo.id)
    return Restful.success(data={'token': token})


@api_route.route('/member/shareInfo/', methods=['POST'])
def shareInfo():
    url = request.form.get('url')
    member_info = g.member_info
    model_share = WxShareHistory()
    model_share.share_url = url
    model_share.created_time = Helper.geneDatetime()
    if member_info:
        model_share.member_id = member_info.id
    db.session.add(model_share)
    db.session.commit()
    return Restful.success()





